/*
 * Created on Sep 23, 2009
 * This software is for the designated users only and contains privileged, proprietary or private information. 
 * Any other use of it is prohibited.  
 */
package com.googlecode.xbeandatasource.common;

import java.beans.IntrospectionException;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;

import javax.xml.parsers.DocumentBuilder;
import javax.xml.parsers.DocumentBuilderFactory;
import javax.xml.parsers.ParserConfigurationException;
import javax.xml.xpath.XPath;
import javax.xml.xpath.XPathConstants;
import javax.xml.xpath.XPathExpression;
import javax.xml.xpath.XPathExpressionException;
import javax.xml.xpath.XPathFactory;

import org.apache.commons.betwixt.io.BeanWriter;
import org.w3c.dom.Document;
import org.xml.sax.SAXException;

/**
 * @author Johny Huang
 *
 */
public class XmlXpathParser {

	public final static Object parse(Object obj,String expression) throws ParserConfigurationException, SAXException, IOException, IntrospectionException, XPathExpressionException{
		DocumentBuilderFactory domFactory = DocumentBuilderFactory.newInstance();
	    domFactory.setNamespaceAware(true); // never forget this!
	    DocumentBuilder builder = domFactory.newDocumentBuilder();
	    
	    ByteArrayOutputStream out=new ByteArrayOutputStream();
	    BeanWriter writer=BeanWriterFactory.newBeanWriter(out, obj);
	    Document doc = builder.parse(new ByteArrayInputStream(out.toByteArray()));
	    System.out.println(out);
	    out.close();

	    XPathFactory factory = XPathFactory.newInstance();
	    XPath xpath = factory.newXPath();
	    XPathExpression expr= xpath.compile(expression);

	    return expr.evaluate(doc, XPathConstants.STRING);
	}
}
